from gui.guiWow import *
from wowMouseKey.wowMouseKeyboard import *
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtNetwork import QLocalSocket, QLocalServer
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

from util.memoryUtil import *
from util.configUtil import *
from util.FileUtil import *
from util.mainUtil import *
import logging.config
from logging.handlers import RotatingFileHandler

import win32api, win32gui, win32con, win32print
import os

import numpy as np
from PIL import ImageGrab, Image, ImageDraw, ImageFont

import subprocess

logging.config.fileConfig("./util/logging.conf")
logging.basicConfig(filename='yhbtestingameing.log', level=logging.DEBUG, force=True)
log = logging.getLogger("example")
fileFullPath = './wowCache.txt'
fileObj = FileUtil()


class mywindow(QtWidgets.QMainWindow, Ui_MainWindow):
    # 基于UI半透明界面的全局变量区
    # 当前正在运行的按键和鼠标(防止重复按键)
    RUNNING_KEY_POOL = []
    # 新引入的redis，用于控制进程，线程，间的控制
    # redis_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, password='', db=0)
    # redis_conn = redis.Redis(connection_pool=redis_pool)
    stopLoop = False

    def __init__(self):
        super(mywindow, self).__init__()
        self.setupUi(self)
        self.setMouseTracking(True)

    # 不工作，后期再来调试
    def mouseMoveEvent(self, e):
        x = e.x()
        y = e.y()
        text = "x: {0},  y: {1}".format(x, y)
        # self.label.setText(text)
        print(text)
        self.setWindowTitle(text)


# 全局变量
global ui
global MainWindow
global schedulerInGame

global objDisplayWeCanChat
global triggerWeCanChat
# 因为经常忘记切换，因此画一个绿色地块，绿灯行，代表文字才可以发出去。（后面在界面层面，也加个定时器来进行多线程并发循环）
objDisplayWeCanChat = BackgroundScheduler()
# seconds=1, 有时候，秒级别的重复调用评率是不够的，因此可以换成比1秒更小的，否则很快被游戏的高帧率刷下去了
triggerWeCanChat = IntervalTrigger(seconds=0.09)


#  自定义的槽函数
def tabfun(index):
    print("点击了第:" + "  " + str(index) + ",个标签页")
    if index == 0:
        # 停止游戏，切换到中文进行聊天
        change_lan(Lan.ZH)
        pauseListen(False)
        terminateAllThreadPool()
        freeThreadPool()
        objDisplayWeCanChat.remove_all_jobs()
        objDisplayWeCanChat.add_job(func=displayWeCanChat, trigger=triggerWeCanChat,
                                    next_run_time=datetime.datetime.now(), id='yehaiboWeCanChat')
        # bobjDisplayWeCanChat.add_job(objPlayer.schedulerAction, triggerInGame, id='yehaibo')
        if objDisplayWeCanChat.running != True:
            objDisplayWeCanChat.start()
    elif index == 1:
        # 切换到英文，准备开始自动游戏
        change_lan(Lan.EN)
        pauseListen(False)
        # if objDisplayWeCanChat.running == True:
        #     log.info('stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!stop!!!')
        #     objDisplayWeCanChat.pause()
        objDisplayWeCanChat.remove_all_jobs()
    elif index == 2:
        change_lan(Lan.EN)
        objPlayer = oo(ui.comboBox.currentText(), ui, MainWindow)

        # pauseListen(False)
    elif index == 3:
        change_lan(Lan.EN)
        pauseListen(False)
    return


'''
            魔兽世界中得桌面显示游戏界面，自己键盘数据都在界面中操作，通过下面得api，也可以将识别出来得框画到魔兽世界显示得界面上
            conda activate wow3.6
            pip install pywin32==300
    '''


def pushButtonStartlistener_click():
    # 继续监听/启动监听
    resumeListen(True)
    # 把当前选择的职业文本传递过去，这样才能实现python的多肽
    log.debug('当前选择的职业为:' + ui.comboBox.currentText())
    objPlayer = oo(ui.comboBox.currentText(), ui, MainWindow)
    # 全局定时执行的一个动作
    triggerInGame = IntervalTrigger(seconds=5)
    schedulerInGame.remove_all_jobs()
    schedulerInGame.add_job(objPlayer.schedulerAction, triggerInGame, id='yehaibo')
    # schedulerInGame.state
    if schedulerInGame.running != True:
        schedulerInGame.start()
    log.debug('**********************************************************************************************')
    # 测试ui能访问到的界面元素
    # ui.checkBox_SM_Jump2Wolf.isChecked()
    # 写文件，到下次重新启动程序的时候，可以直接从文件中读取上次选中的职业，这样不用每次慌张地去二次选择职业
    fileObj.writeFile(fileFullPath, ui.comboBox.currentText())
    # aa = fileObj.readFile(fileFullPath)
    return


def pushButtonStopListener_click():
    # 暂停监听/停止监听
    pauseListen(False)
    # 全局定时器自动执行停止
    schedulerInGame.pause_job(job_id='yehaibo')
    return


def pushButtonCatchVideo_click():
    # 捕捉的捕字，点击
    # lineEdit_X
    # lineEdit_Y
    # lineEdit_width
    # lineEdit_height
    avg_color = 0
    im = ImageGrab.grab(
        bbox=(
            int(ui.lineEdit_X.text()), int(ui.lineEdit_Y.text()),
            int(ui.lineEdit_X.text()) + int(ui.lineEdit_width.text()),
            int(ui.lineEdit_Y.text()) + int(ui.lineEdit_height.text())))  # X1,Y1,X2,Y2
    im_numpy = np.array(im.getdata(), dtype='uint8').reshape((im.size[1], im.size[0], 3))
    im_pil = Image.fromarray(im_numpy)
    r, g, b = im_pil.split()  # 分离三通道
    if ui.comboBox_RGB.currentText() == 'r':
        r.thumbnail((1, 1))  # 图片缩放为一个像素点
        avg_color = r.getpixel((0, 0))
    elif ui.comboBox_RGB.currentText() == 'g':
        g.thumbnail((1, 1))  # 图片缩放为一个像素点
        avg_color = g.getpixel((0, 0))
    elif ui.comboBox_RGB.currentText() == 'b':
        b.thumbnail((1, 1))  # 图片缩放为一个像素点
        avg_color = b.getpixel((0, 0))

    ui.plainTextEdit_ShowResult.appendPlainText(str(avg_color))
    return


def pushButtonClearVideo_click():
    ui.plainTextEdit_ShowResult.clear()
    return


def pushButton_10v10():
    # 评级中不带自动选择队伍
    t10v10 = threading.Thread(target=pushButton_10v10_in_thread)
    t10v10.start()
    return


def pushButton_10v10_Full_SelectTeam():
    # 评级中带自动选择队伍，在夜间全自动运行和判断
    t10v10 = threading.Thread(target=pushButton_10v10_in_thread)
    t10v10.start()
    return


def pushButton_10v10_in_thread():
    player.sleep(2)
    player.stopLoop = False
    while player.stopLoop == False:

        for i in range(1, 4):
            # 取消复活(可能和职业选择的勾勾冲突，因此向前调整一小点)
            player.ExecutemouseMove(923, 183 + i * 4)
            player.ExecutemouseLeftClick()
            player.sleep(0.1)

        for i in range(1, 30):
            # 坦克、治疗的职业选择，和进入评级，两个一起确认(团本的确认也在一起了)
            player.ExecutemouseMove(929, 280 + i * 4)
            player.ExecutemouseLeftClick()
            player.sleep(0.1)

        for i in range(1, 8):
            # SKada+团长就位确认
            player.ExecutemouseMove(906, 564 + i * 4)
            player.ExecutemouseLeftClick()
            player.sleep(0.1)

        for i in range(1, 14):
            # 退出比赛
            player.ExecutemouseMove(951, 780 + i * 4)
            player.ExecutemouseLeftClick()
            player.sleep(0.1)
        player.click(player.kb, Key.space, 1)
        player.sleep(0.4)
    return


def pushButton_stop():
    player.stopLoop = True
    return


def pushButtonWA():
    # wa需要的所有位置矫正
    font = ImageFont.truetype("simsun.ttc", 40, encoding="unic")  # 设置字体
    # 画框，弹出截图，来定位截图位置是否正确
    hDC = win32gui.GetDC(0)
    w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)  # 横向分辨率
    h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)  # 纵向分辨率
    # 从配置文件中读取配置，确定左下角的wa的方块的位置是否正确,在弹出截图后，进行调整。
    imButton1 = ImageGrab.grab(
        bbox=(0, 0, w, h))  # X1,Y1,X2,Y2
    imButton1_numpy = np.array(imButton1.getdata(), dtype='uint8').reshape(
        (imButton1.size[1], imButton1.size[0], 3))
    imButton1_pil = Image.fromarray(imButton1_numpy)
    draw = ImageDraw.Draw(imButton1)

    # ★★★★★★★★★★★★★★★★★★★★★★★目前start★★★★★★★★★★★★★★★★★★★★★★★★★★#
    # 绘制矩形(背景不透明)
    # draw.rectangle((100, 200, 300, 400), 'black', 'red')
    # 画矩形（从魔兽世界中的wa插件，左下角的红色信号放大正方形方块的位置调整）
    # 方块1
    wWASquareLeftButton = int(getIni("./util", "xyStatusSquare", "width"))
    xCenterWASquareLeftButton = int(getIni("./util", "xyStatusSquare", "x1"))
    yCenterWASquareLeftButton = int(getIni("./util", "xyStatusSquare", "y1"))

    for i in range(0, 9):
        # 循环画多个方块的位置（中间把wa的红色方块包住）
        rectangleBy4Line(xCenterWASquareLeftButton - wWASquareLeftButton / 2 + i * wWASquareLeftButton,
                         yCenterWASquareLeftButton - wWASquareLeftButton / 2,
                         xCenterWASquareLeftButton + wWASquareLeftButton / 2 + i * wWASquareLeftButton,
                         yCenterWASquareLeftButton + wWASquareLeftButton / 2, draw, 4, (0, 255, 0))
    # 龙希尔的蓄力条
    wWACastdBar = int(getIni("./util", "xyCastBar", "width"))
    xCenterWACastBar = int(getIni("./util", "xyCastBar", "x1"))
    yCenterWACastBar = int(getIni("./util", "xyCastBar", "y1"))

    rectangleBy4Line(xCenterWACastBar, yCenterWACastBar - 10, xCenterWACastBar + wWACastdBar, yCenterWACastBar + 10,
                     draw, 3, (0, 255, 0))

    # wa自己的血条
    wWABloodBar = int(getIni("./util", "xyBloodBar", "width"))
    xCenterWABloodBar = int(getIni("./util", "xyBloodBar", "x1"))
    yCenterWABloodBar = int(getIni("./util", "xyBloodBar", "y1"))

    rectangleBy4Line(xCenterWABloodBar, yCenterWABloodBar - 10, xCenterWABloodBar + wWABloodBar, yCenterWABloodBar + 10,
                     draw, 3, (255, 255, 0))
    draw.text((xCenterWABloodBar - 150, yCenterWABloodBar - 90), u'wa自己的血条(下面是自己的血条[黄色口框]);设置焦点坦克血条(绿色口框);魔法条(蓝色口框)', 'fuchsia',
              font)

    # wa自己血条下面的焦点的血条(坦克焦点)
    gap1InY = 39
    rectangleBy4Line(xCenterWABloodBar, yCenterWABloodBar - 10 + gap1InY, xCenterWABloodBar + wWABloodBar, yCenterWABloodBar + 10 + gap1InY,
                     draw, 3, (0, 255, 0))

    # 魔法条
    wWAMagicBar = int(getIni("./util", "xyMagicBar", "width"))
    xCenterWAMagicBar = int(getIni("./util", "xyMagicBar", "x1"))
    yCenterWAMagicBar = int(getIni("./util", "xyMagicBar", "y1"))
    rectangleBy4Line(xCenterWAMagicBar, yCenterWAMagicBar - 10, xCenterWAMagicBar + wWAMagicBar, yCenterWAMagicBar + 10,
                     draw, 3, (0, 0, 255))

    # 能量条
    wWAEnergyBar = int(getIni("./util", "xyEnergyBar", "width"))
    xCenterWAEnergyBar = int(getIni("./util", "xyEnergyBar", "x1"))
    yCenterWAEnergyBar = int(getIni("./util", "xyEnergyBar", "y1"))

    rectangleBy4Line(xCenterWAEnergyBar, yCenterWAEnergyBar - 10, xCenterWAEnergyBar + wWAEnergyBar,
                     yCenterWAEnergyBar + 10,
                     draw, 3, (0, 255, 0))

    # 圣骑士能量星星（盗贼能量星星）
    wWStar = int(getIni("./util", "xyStar", "width"))
    xCenterStar = int(getIni("./util", "xyStar", "x1"))
    yCenterStar = int(getIni("./util", "xyStar", "y1"))
    for i in range(0, 6):
        rectangleBy4Line(xCenterStar - wWStar / 2 + i * wWStar,
                         yCenterStar - wWStar / 2,
                         xCenterStar + wWStar / 2 + i * wWStar,
                         yCenterStar + wWStar / 2, draw, 4, (255, 255, 0))

    # MP法力条
    # wWStar = int(getIni("./util", "xyMagicBar", "width"))
    # xCenterStar = int(getIni("./util", "xyMagicBar", "x1"))
    # yCenterStar = int(getIni("./util", "xyMagicBar", "y1"))

    # ws综合插件（活血酒，天神酒检测），两个绿色圆圈点，可能变红的。
    wWSZA = int(getIni("./util", "wst_za_red", "w"))
    hWSZA = int(getIni("./util", "wst_za_red", "h"))
    xWSZA = int(getIni("./util", "wst_za_red", "x"))
    yWSZA = int(getIni("./util", "wst_za_red", "y"))
    avgColorWSZA = int(getIni("./util", "wst_za_red", "avgColor"))
    rectangleBy4Line(xWSZA, yWSZA, xWSZA + wWSZA, yWSZA + hWSZA,
                     draw, 3, (0, 255, 255))

    # 治疗配合的continue healer插件位置,上下左右外围方框的，口字形区域
    Heal5BarX1 = int(getIni("./util", "heal5bar", "x1"))
    Heal5BarY1 = int(getIni("./util", "heal5bar", "y1"))
    Heal5BarX2 = int(getIni("./util", "heal5bar", "x2"))
    Heal5BarY2 = int(getIni("./util", "heal5bar", "y2"))
    rectangleBy4Line(Heal5BarX1, Heal5BarY1, Heal5BarX2, Heal5BarY2,
                     draw, 2, (0, 255, 0))

    # 绘制文本
    draw.text((xCenterWASquareLeftButton, yCenterWASquareLeftButton - 200), u'打开WA插件后，请调整方块位置，保证红方块在绿框的正中心', 'fuchsia',
              font)
    draw.text((xWSZA-300, yWSZA - 100), u'武僧T的神级插件定制的位置(蓝色两个横着的正方形拼接成的长方形),平均值为:' + str(avgColorWSZA), 'fuchsia',
              font)

    draw.text((xCenterWASquareLeftButton, yCenterWASquareLeftButton - 400),
              u'黄色为骑士能量豆子星星矫正框', 'fuchsia',
              font)
    #★★★★★★★★★★★★★★★★★★★★★★★目前end★★★★★★★★★★★★★★★★★★★★★★★★★★#
    # ddyy的zfx检测
    # Heal5BarX1 = getIniInt("./util", "xyStatusSquare", "x1")
    # Heal5BarY1 = getIniInt("./util", "xyStatusSquare", "y1")
    # Heal5BarX2 = Heal5BarX1 +8
    # Heal5BarY2 = Heal5BarY1 +8
    # rectangleBy4Line(Heal5BarX1, Heal5BarY1, Heal5BarX2, Heal5BarY2,
    #                  draw, 2, (0, 255, 0))
    # log.info("密数万象监控的值:x" + str(Heal5BarX1) + ",Y:" + str(Heal5BarY1))
    #
    # draw.text((600, 800),
    #           u'自行判断点的位置是否准了,x:' + str(Heal5BarX1) + "y:" + str(Heal5BarY1), 'fuchsia',
    #           font)

    imButton1.show()
    return

def pushButtonWA_radom():
    # 自己可以随意修改的方式，及时解决屏幕上的坐标不准的问题，代码随意动，反正调试方便
    # wa需要的所有位置矫正
    font = ImageFont.truetype("simsun.ttc", 40, encoding="unic")  # 设置字体
    # 画框，弹出截图，来定位截图位置是否正确
    hDC = win32gui.GetDC(0)
    wa = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)  # 横向分辨率
    hb = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)  # 纵向分辨率
    # 从配置文件中读取配置，确定左下角的wa的方块的位置是否正确,在弹出截图后，进行调整。
    imButtonFull = ImageGrab.grab(
        bbox=(0, 0, wa, hb))  # X1,Y1,X2,Y2
    imButtonFull_numpy = np.array(imButtonFull.getdata(), dtype='uint8').reshape(
        (imButtonFull.size[1], imButtonFull.size[0], 3))
    imButton1_pil = Image.fromarray(imButtonFull_numpy)
    draw = ImageDraw.Draw(imButtonFull)


    # ddyy的zfx【正方形】检测
    x1 = getIniInt("./util", "xyStatusSquare", "x1")
    y1 = getIniInt("./util", "xyStatusSquare", "y1")
    w = 8
    h = 8
    x2 = x1 + w
    y2 = y1 + h
    rectangleBy4Line(x1, y1, x2, y2,
                     draw, 2, (0, 255, 0))

    # 抽取哪个像素通道的值
    RGBMode = 'r'
    # 获取的像素值
    imButton1 = ImageGrab.grab(
        bbox=(x1 - w / 2, y1 - h / 2, x1 + w / 2, y1 + h / 2))  # X1,Y1,X2,Y2
    imButton1_numpy = np.array(imButton1.getdata(), dtype='uint8').reshape(
        (imButton1.size[1], imButton1.size[0], 3))
    imButton1_pil = Image.fromarray(imButton1_numpy)
    rButton1, gButton1, bButton1 = imButton1_pil.split()  # 分离三通道
    avgButton1_color = 0
    if RGBMode == 'r':
        rButton1.thumbnail((1, 1))  # 图片缩放为一个像素点
        avgButton1_color = rButton1.getpixel((0, 0))
    elif RGBMode == 'g':
        gButton1.thumbnail((1, 1))  # 图片缩放为一个像素点
        avgButton1_color = gButton1.getpixel((0, 0))
    elif RGBMode == 'b':
        bButton1.thumbnail((1, 1))  # 图片缩放为一个像素点
        avgButton1_color = bButton1.getpixel((0, 0))

    draw.text((600, 800),
              u'自行的临时代码判断点的位置是否准了,x: ' + str(x1) + "      ,y: " + str(y1) + ",    截取的通道:" + RGBMode + ",的像素值为:" + str(avgButton1_color), 'fuchsia',
              font)

    imButtonFull.show()
    return


def pushButtonXYWidthHeight():
    font = ImageFont.truetype("simsun.ttc", 40, encoding="unic")  # 设置字体
    # 画框，弹出截图，来定位截图位置是否正确
    hDC = win32gui.GetDC(0)
    w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)  # 横向分辨率
    h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)  # 纵向分辨率
    # 从配置文件中读取配置，确定左下角的wa的方块的位置是否正确,在弹出截图后，进行调整。
    imButton1 = ImageGrab.grab(
        bbox=(0, 0, w, h))  # X1,Y1,X2,Y2
    imButton1_numpy = np.array(imButton1.getdata(), dtype='uint8').reshape(
        (imButton1.size[1], imButton1.size[0], 3))
    imButton1_pil = Image.fromarray(imButton1_numpy)
    draw = ImageDraw.Draw(imButton1)

    if ui.lineEdit_X.text() == '' or ui.lineEdit_Y.text() == '' or ui.lineEdit_width.text() == '' or ui.lineEdit_height.text() == '':
        pass
    else:
        rectangleBy4Line(int(ui.lineEdit_X.text()), int(ui.lineEdit_Y.text()),
                         int(ui.lineEdit_X.text()) + int(ui.lineEdit_width.text()),
                         int(ui.lineEdit_Y.text()) + int(ui.lineEdit_height.text()),
                         draw, 3, (0, 255, 0))
        draw.text((800, 800 - 100), u'画出x,y,w,h四个框中的值，以确定在实际操作系统中的位置:', 'fuchsia',
                  font)
        imButton1.show()
    return


def organizeTab(ui):
    # 界面一打开，就会执行这里
    log.debug("UI界面启动执行的初始化，其中 startListen ，是永远不会第二次执行到这里的")
    startListen()  # 永远不会第二次执行到这里，因此不会触发异常，大的控制，全部在tab切换的事件那里去控制了
    pauseListen(False)  # 我们一开始实际就启动了监听，之后在界面初始化之初，就把他停止在这里了|主要就是通过这里的 False 来控制默认都不监听
    ui.tabWidget.setCurrentIndex(0)
    ui.tabWidget.currentChanged['int'].connect(tabfun)

    scheduler = BackgroundScheduler()
    trigger1 = IntervalTrigger(seconds=int(getIni("./util", "memory", "interval")))
    scheduler.add_job(freePythonMemory, trigger1)

    trigger2 = IntervalTrigger(seconds=int(getIni("./util", "threadPool", "interval")))
    scheduler.add_job(freeThreadPool, trigger2)
    scheduler.start()

    # 按键的事件绑定
    ui.pushButtonStartlistener.clicked.connect(pushButtonStartlistener_click)
    ui.pushButtonStopListener.clicked.connect(pushButtonStopListener_click)
    ui.pushButtonRestart.clicked.connect(restart)
    # 捕捉视频中的平均像素值
    ui.pushButtonCatchVideo.clicked.connect(pushButtonCatchVideo_click)
    ui.pushButtonClearVideo.clicked.connect(pushButtonClearVideo_click)

    # 排评级(不带自动选择队伍)
    ui.pushButton_10v10.clicked.connect(pushButton_10v10)
    # 评级带自动选择队伍
    ui.pushButton_10v10_Full_SelectTeam.clicked.connect(pushButton_10v10_Full_SelectTeam)

    ui.pushButton_stop.clicked.connect(pushButton_stop)

    ui.pushButtonReboot.clicked.connect(restart)
    ui.pushButtonWA.clicked.connect(pushButtonWA)
    ui.pushButtonXYWidthHeight.clicked.connect(pushButtonXYWidthHeight)
    ui.pushButtonRadom.clicked.connect(pushButtonWA_radom)

    # 在启动后，读取上次的wow文件

    if (os.path.exists(fileFullPath) == False):
        # 文件不存在，第一次的新创建
        fileObj.writeFile(fileFullPath, ui.comboBox.currentText())
    else:
        # 已经存在了，就需要读取，并且选择selectItewm
        playerFromPreviousFile = fileObj.readFile(fileFullPath)
        ui.comboBox.setCurrentText(playerFromPreviousFile)
    return


def setMainWindowAttr(MainWindow):
    # 对右下角的窗口属性进行设置
    MainWindow.setFixedSize(MainWindow.width(), MainWindow.height())  # 禁止调整窗口大小
    MainWindow.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)  # 这一句的作用，是把窗口始终在最前面显示。
    MainWindow.setWindowOpacity(0.2)  # 设置窗口透明度
    MainWindow.move(int(getIni("./util", "mainWindowXY", "x1")),
                    int(getIni("./util", "mainWindowXY", "y1")))  # 调整窗口的x，y坐标位置
    # 显示鼠标的坐标
    # MainWindow.setWindowTitle('test1')

    return


def restart():
    # 执行之前，先要把停掉
    # ★★★★★★★★★★★★★★★★★★★★★★在 Player.py中搜索 batFilePath 关键字，可以搜索到通过windows建，触发程序终止的程序
    # pauseListen(False)
    # 避免批处理弹出黑框
    # win32api.ShellExecute(0, 'open', getIni("../util", "bat", "batFilePath"), '', '', 0)

    log.debug('本机用户名:'+os.getlogin())
    if os.getlogin() == 'Hasee':
        # 在PC机器，笔记本上是这个文件
        vbs_file = 'ddyy.vbs'
        subprocess.call(['cscript', vbs_file], shell=True)
    else:
        # 在远程云电脑，又是另外一些目录和文件了(cyycloud.vbs)
        vbs_file = 'cyycloud.vbs'
        subprocess.call(['cscript', vbs_file], shell=True)

    return


if __name__ == '__main__':
    change_lan(Lan.EN)
    app = QApplication(sys.argv)
    # 保证只有一个实例在运行
    serverName = 'myuniqueservername'
    socket = QLocalSocket()
    socket.connectToServer(serverName)
    # 如果连接成功，表明server已经存在，当前已有实例在运行
    if socket.waitForConnected(500):
        # app.quit()
        log.info('第二次启动app界面，不允许，因此强制关闭')
        sys.exit()

        # 没有实例运行，创建服务器
    localServer = QLocalServer()
    localServer.listen(serverName)
    try:
        MainWindow = QMainWindow()
        schedulerInGame = BackgroundScheduler()
        # 修改为全局变量
        ui = mywindow()
        ui.setupUi(MainWindow)

        # 设置窗口的一些属性
        setMainWindowAttr(MainWindow)
        MainWindow.show()
        organizeTab(ui)
        sys.exit(app.exec_())
    finally:
        localServer.close()
